package com.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.reggie.common.BaseContext;
import com.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 检查用户是否已经完成登录
 */
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*") //过滤器配置
@Slf4j
public class LoginCheckFilter implements Filter{  //抽象类，需要实现方法doFilter
    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //强转一下,向下转型
        HttpServletRequest request = (HttpServletRequest) servletRequest;  //强制类型转换
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1、获取本次请求的URL
        String requestURl = request.getRequestURI();

        log.info("拦截到请求：{}",requestURl);  //输出日志  {}占位符输出内容取决参数

        //2、本次请求是否需要处理，通过定义请求路径放行来判断
        String[] urls = new String[] {
                "/employee/login",      //登录请求
                "/employee/loginout",   //登出请求
                "/backend/**",          //静态资源请求
                "/front/**",
                "/common/**" ,           //上传页面请求
                "/user/sendMsg",         //前端发送验证码请求
                "/user/login",          //前端登录请求
                "/doc.html",            //接口文档
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"

        };//定义放行url
        boolean check = check(urls, requestURl);

        //3、如果不需要处理，则直接放行
        if(check){
            log.info("本次请求{}不需要处理",requestURl);
            filterChain.doFilter(request,response);    //放行请求
            return;
        }

        //4-1、后端判断登录状态，如果已登录，则直接放行
        if(request.getSession().getAttribute("employee")!=null){     //从session中取出用户登录状态
        //if(redisTemplate.opsForValue().get("employee")!=null){    //redis版本
            log.info("用户已登录，用户id为：{}",request.getSession().getAttribute("employee"));

            Long empId= (Long) request.getSession().getAttribute("employee");
            //Long empId= (Long) redisTemplate.opsForValue().get("employee"); //redis版本
            BaseContext.setCurrentId(empId);

//            long id = Thread.currentThread().getId();         //获取当前处理这次请求的线程id
//            log.info("线程id为：{}",id);

            filterChain.doFilter(request,response);    //放行请求
            return;
        }

        //4-2、前端判断登录状态，如果已登录，则直接放行
        if(request.getSession().getAttribute("user")!=null){     //从session中取出用户登录状态
        //if(redisTemplate.opsForValue().get("user")!=null){  //redis版本
            log.info("用户已登录，用户id为：{}",request.getSession().getAttribute("user"));

            Long useId= (Long) request.getSession().getAttribute("user");
            //Long useId= (Long) redisTemplate.opsForValue().get("user");    //redis版本
            BaseContext.setCurrentId(useId);

//            long id = Thread.currentThread().getId();         //获取当前处理这次请求的线程id
//            log.info("线程id为：{}",id);

            filterChain.doFilter(request,response);    //放行请求
            return;
        }

        log.info("用户未登录");
        //5、如果未登录则返回未登录结果，通过输出流方式向客户端页面响应数据
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));   //把R对象转为json数据写回使前端页面自行响应
        return;
        //log.info("拦截到请求：{}",request.getRequestURI());
        //filterChain.doFilter(request,response);    //放行请求
    }

    /**
     * 路径匹配，检查本次请求是否放行
     * @param urls
     * @param requestURL
     * @return
     */
    public boolean check(String[] urls,String requestURL){
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url,requestURL);
            if(match){
                return true;
            }

        }
        return false;
    }
}
